<template>
  <div class="container">
    <div class="top-row">
      <div class="title"><span>优惠券管理&nbsp;</span> <svgIcon name="coupon" color="#fd6112" size="20"></svgIcon></div>
      <el-button @click="saveComponentState.visible = true">+ 创建</el-button>
    </div>
    <div class="body">
      <el-table :data="tableData" stripe style="width: 100%" size="large">
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column prop="name" label="优惠券名称" width="250" />
        <el-table-column label="优惠券类型">
          <template v-slot="{ row }">{{ couponTypeLabelOf(row.type) }}</template>
        </el-table-column>
        <el-table-column label="已使用/已领取/总发行">
          <template v-slot="{ row }">{{ row.usedCount }}/{{ row.issuedCount }}/{{ row.total }}</template>
        </el-table-column>
        <el-table-column label="是否可领取" align="center">
          <template v-slot="{ row }">
            <el-icon v-if="row.status"><Select /></el-icon>
            <el-icon v-else><CloseBold /></el-icon>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-button :link="true" size="small" :icon="Edit" @click="editHandle(row.id)">修改</el-button>
            <el-button :link="true" size="small" :icon="Connection">批量制券（兑换码）</el-button>
            <el-button :link="true" size="small" :icon="Delete" @click="deleteHandle(row.id)" class="delBut">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <SaveDialog
      title="店铺优惠券"
      v-model:visible="saveComponentState.visible"
      :id="saveComponentState.form.id"
      @query="saveComponentState.query()"
      @cancel="saveComponentState.cancel()"
      @save="(callback: any) => saveComponentState.save(callback)"
      :width="'55%'"
      class="save-dialog"
    >
      <template #body>
        <el-form ref="name" :model="saveComponentState.form" class="demo-form-inline" :rules="saveComponentState.rules" label-width="150px">
          <el-form-item label="优惠券名称：">
            <el-input v-model="saveComponentState.form.name" style="width: 45%" placeholder="优惠券名称" />
          </el-form-item>
          <el-form-item label="优惠券类型：">
            <el-radio-group v-model="saveComponentState.form.type" class="ml-4">
              <el-radio :value="CouponType.CASH_COUPON">
                <div class="label">
                  <span>代金券（满减）</span>
                  <el-tooltip class="box-item" effect="dark" content="适用商品的总和满足门槛后即可使用" placement="top-start">
                    <el-icon @click.stop><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </el-radio>
              <el-radio :value="CouponType.DISCOUNT_COUPON">
                <div class="label">
                  <span>折扣券&nbsp;</span>
                  <el-tooltip class="box-item" effect="dark" content="购买的商品中包含适用商品，若多个适用于价格最高的进行折扣" placement="top-start">
                    <el-icon @click.stop><QuestionFilled /></el-icon>
                  </el-tooltip>
                </div>
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="优惠券面值：" v-if="saveComponentState.form.type != null">
            <div v-if="saveComponentState.form.type === CouponType.CASH_COUPON">
              <el-input size="small" style="width: 20%" v-model="saveComponentState.form.parValue" />&nbsp;元 ,&nbsp;&nbsp;满&nbsp;<el-input
                style="width: 20%"
                size="small"
                v-model="saveComponentState.form.thresholdAmount"
              />&nbsp;可用
            </div>

            <div v-if="saveComponentState.form.type === CouponType.DISCOUNT_COUPON">
              <el-input
                size="small"
                style="width: 200px"
                placeholder="0.01~9.99"
                v-model="saveComponentState.form.parValue"
                @change="(value:string)=>saveComponentState.form.parValue = resolveToDiscountValue(value)"
              />&nbsp;折
            </div>
          </el-form-item>
          <el-form-item label="使用有效方式：">
            <div class="item-value-box">
              <el-radio-group v-model="saveComponentState.form.usageValidityPeriodType">
                <el-radio :value="1">固定日期范围内</el-radio>
                <el-radio :value="2">领取后固定天数内</el-radio>
              </el-radio-group>
              <div class="item-value-box-row">
                <el-date-picker
                  v-model="saveComponentState.form._usageDateTimeRange"
                  @blur="
                    () => {
                      if (saveComponentState.form._usageDateTimeRange != null) {
                        saveComponentState.form.usageStartTime = saveComponentState.form._usageDateTimeRange[0]
                        saveComponentState.form.usageEndTime = saveComponentState.form._usageDateTimeRange[1]
                      }
                    }
                  "
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  v-if="saveComponentState.form.usageValidityPeriodType === 1"
                  size="small"
                  type="datetimerange"
                  range-separator="到"
                  start-placeholder="开始日期时间"
                  end-placeholder="结束日期时间"
                />
                <div v-if="saveComponentState.form.usageValidityPeriodType === 2">
                  <el-input-number
                    v-model="saveComponentState.form.usagePeriodDays"
                    size="small"
                    :min="1"
                    :max="180"
                    controls-position="right"
                  />&nbsp;&nbsp;天
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="领取方法：">
            <el-radio-group v-model="saveComponentState.form.obtainWay">
              <el-radio :value="1">店铺展示领取</el-radio>
              <el-radio :value="-1">兑换码领取</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="适用商品：">
            <div class="item-value-box">
              <el-radio-group v-model="saveComponentState.form.applicableType" class="ml-4">
                <el-radio :value="ApplicableType.NO_RESTRICTIONS">全部商品</el-radio>
                <el-radio :value="ApplicableType.APPLY_CATEGORY">指定类别</el-radio>
                <el-radio :value="ApplicableType.APPLY_PRODUCT">指定商品</el-radio>
              </el-radio-group>
              <div class="item-value-box-row" v-if="saveComponentState.form.applicableType !== ApplicableType.NO_RESTRICTIONS">
                <el-select size="small" v-model="saveComponentState.form.applicableLogic" style="width: 160px" placeholder="适用逻辑">
                  <el-option label="适用选中的" :value="1" />
                  <el-option label="排除选中的" :value="2" />
                </el-select>
                <el-tree-select
                  v-if="saveComponentState.form.applicableType === ApplicableType.APPLY_CATEGORY"
                  :props="{ label: 'name', children: 'none' }"
                  node-key="id"
                  v-model="saveComponentState.form._applicableValues"
                  @change="() => (saveComponentState.form.applicableValues = saveComponentState.form._applicableValues.join(','))"
                  placeholder="请选择商品类别"
                  size="small"
                  :data="dishTree"
                  multiple
                  :render-after-expand="false"
                  show-checkbox
                />
                <el-tree-select
                  v-else
                  :props="{ label: 'name', children: 'dishList' }"
                  node-key="id"
                  v-model="saveComponentState.form._applicableValues"
                  @change="() => (saveComponentState.form.applicableValues = saveComponentState.form._applicableValues.join(','))"
                  placeholder="请选择商品"
                  size="small"
                  :data="dishTree"
                  multiple
                  :render-after-expand="false"
                  show-checkbox
                />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="是否可叠加：">
            <el-radio-group v-model="saveComponentState.form.isStackable">
              <el-radio :value="false">不可叠加</el-radio>
              <el-radio :value="true">可叠加</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="张数限制：">
            总张数&nbsp;<el-input
              style="width: 20%"
              size="small"
              v-model.number="saveComponentState.form.total"
            />&nbsp;张&nbsp;&nbsp;每人限领&nbsp;<el-input
              style="width: 20%"
              v-model.number="saveComponentState.form.perPersonLimit"
              size="small"
            />&nbsp;张
          </el-form-item>
          <el-form-item label="是否可领取：">
            <el-switch
              v-model="saveComponentState.form.status"
              :active-value="1"
              :inactive-value="0"
              style="

--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
            />
          </el-form-item>
        </el-form>
      </template>
    </SaveDialog>
  </div>
</template>

<script setup lang="ts">
import ComponentHat from '@/plugins/type'
import CouponBatch from '@/types/entity/CouponBatch'
import { getCurrentInstance, nextTick, onMounted, reactive, ref, watch } from 'vue'
import DishCategory from '@/types/entity/DishCategory'
import SaveDialog from '@/components/save-dialog/index.vue'
import { ShopCouponBatchDTO } from '@/types/param/coupon'
import { Back, Delete, Edit, Select, CloseBold, Connection, QuestionFilled } from '@element-plus/icons-vue'
import { ApplicableType } from '@/enums/ApplicableType'
import { CouponType, couponTypeLabelOf } from '@/enums/CouponType'
const { $store, $API, $modal } = <ComponentHat>getCurrentInstance().proxy
const dishTree = ref<DishCategory[]>(null)
const tableData = ref<CouponBatch[]>(null)
async function loadShopDishTree() {
  const result = await $API.dishCategory.getDishCategoryTree()
  if (result.success) dishTree.value = result.data ?? []
}
onMounted(async () => {
  refreshList()
})
// 当点击编辑活动时
const editHandle = (id: number) => {
  saveComponentState.form.id = id
  saveComponentState.visible = true
}
// 点击删除按钮时
const deleteHandle = async (id: number) => {
  const result = await $API.couponBatch.deleteShopCouponBatch(id)
  if (result.success) {
    $modal.msgSuccess('删除活动成功！')
    // 刷新当前页数据
    refreshList()
  } else {
    $modal.msgError('删除活动失败！' + result.message)
  }
}
async function refreshList() {
  const result = await $API.couponBatch.queryShopCouponBatchList()
  if (result.success) tableData.value = result.data
}
// 将输入的值解析为折扣值
function resolveToDiscountValue(value: string) {
  const parValue = parseFloat(value)
  if (isNaN(parValue) || parValue < 0.01) {
    return 0.01
  } else if (parValue > 9.99) {
    return 9.99
  } else {
    return parValue
  }
}

const saveComponentState = reactive({
  rules: {
    // name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
    // sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
  },
  visible: false,
  form: {
    id: null
  } as ShopCouponBatchDTO,
  async query() {
    await loadShopDishTree()
    const selectDishCategoryResult = await $API.couponBatch.queryShopCouponBatch(saveComponentState.form.id)
    if (!selectDishCategoryResult.success) {
      $modal.msgError(selectDishCategoryResult.message)
      return false
    }
    Object.assign(saveComponentState.form, selectDishCategoryResult.data)
    // 回显兼容
    saveComponentState.form._applicableValues = (saveComponentState.form.applicableValues ?? '').split(',')
    this.form._usageDateTimeRange = [saveComponentState.form.usageStartTime, saveComponentState.form.usageEndTime]

    return true
  },
  async save(callback: (success: boolean) => void) {
    console.log('提交的内容：', saveComponentState.form)
    const result = await $API.couponBatch.putShopCouponBatch(this.form)
    callback(result.success)
    // 将form置空
    if (result.success) {
      refreshList()
      this.form = new ShopCouponBatchDTO()
    }
  },
  cancel() {
    // 将form置空
    console.log('置空')
    this.form = new ShopCouponBatchDTO()
  }
})

// 改变-置空对应的值的一些watch
watch(
  () => saveComponentState.form.type,
  (newValue, oldValue) => {
    if (newValue != null && oldValue != null && newValue != oldValue) {
      saveComponentState.form.thresholdAmount = saveComponentState.form.parValue = null
    }
  }
)
watch(
  () => saveComponentState.form.usageValidityPeriodType,
  (newValue, oldValue) => {
    if (newValue != null && oldValue != null && newValue != oldValue) {
      saveComponentState.form._usageDateTimeRange = ['', '']
      saveComponentState.form.usageStartTime = saveComponentState.form.usageEndTime = null
      saveComponentState.form.usagePeriodDays = null
    }
  }
)
watch(
  () => saveComponentState.form.applicableType,
  (newValue, oldValue) => {
    if (dishTree.value == null) loadShopDishTree()
    if (newValue != null && oldValue != null) {
      // 置空一些相关内容
      saveComponentState.form._applicableValues = []
      saveComponentState.form.applicableValues = null
      // // 刷新分类树组件
      // saveComponentState.form.applicableType = null
      // nextTick(() => (saveComponentState.form.applicableType = newValue))
    }
  }
)
</script>

<style scoped lang="scss">
.container {
  box-sizing: border-box;

  .top-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    padding: 0 20px;
    height: 50px;
    font-size: 15px;
    border-bottom: 1px solid #f6f6f6;
    background-color: #fff;

    .title {
      display: flex;
      align-items: center;
      font-size: 16px;
    }
  }

  .body {
    padding: 0 20px;
    box-sizing: border-box;
    background-color: #fff;
  }

  .save-dialog {
    .item-value-box {
      display: flex;
      flex-direction: column;
      overflow: hidden;

      .item-value-box-row {
        flex-grow: 1;
        display: flex;
        margin-top: 10px;
      }
    }

    .label {
      display: flex;
      align-items: center;
    }
  }
}
</style>
